//
//  AnjiMainViewController_Second.m
//  OASystem
//
//  Created by zhoupengfei on 16/3/26.
//  Copyright © 2016年 zpf. All rights reserved.
//

#import "AnjiMainViewController_Second.h"
#import "MainViewCell.h"
#import "OADueInViewController.h"
#import "OASMSViewController.h"
#import "OAUpComingWorkController.h"
#import "OAToDoWorkViewController.h"
#import "OANoteViewController.h"
#import "OANewInViewController.h"
#import "OANewSendViewController.h"
#import "OAInBoxViewController.h"
#import "OASendMessageViewController.h"
#import "OAHomeEmailViewController.h"
#import "OAAddressViewController.h"
#import "HttpTools.h"
#import "BaseModel.h"
#import "OALoginViewController.h"
#import "AuthHelper.h"

@interface HomeModel : BaseModel

@property(nonatomic,copy)NSString *  exchange;
@property(nonatomic,copy)NSString *  ksmail;
@property(nonatomic,copy)NSString *  mail;
@property(nonatomic,copy)NSString *  offiece;
@property(nonatomic,copy)NSString *  whetherExchange;
@property(nonatomic,copy)NSString *  whetherSms;
@property(nonatomic,copy)NSString * read;
@end

@implementation HomeModel

@end

@interface AnjiMainViewController_Second ()<UICollectionViewDelegateFlowLayout>
@property(nonatomic,strong)NSMutableArray * contentArray;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *followLayout;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property(nonatomic,strong)HomeModel * homeModel;
@property(nonatomic,strong)NSMutableArray * originalData;

@end

@implementation AnjiMainViewController_Second

static NSString * const reuseIdentifier = @"CellIdentifier";

-(NSMutableArray*)contentArray{
    if (_contentArray == nil) {
        _contentArray = [NSMutableArray array];
    }
    return _contentArray;
}

-(void)viewWillAppear:(BOOL)animated{
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"autoLogin"] isEqualToString:@"Y"]) {
        
//        [self updateApp];

    }
    
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray *  array = @[@{@"userId":userId}];;
    [HttpTools requestWithURL:KExchmain arrays:array method:KHomePqwoiunu success:^(id JSON) {
        NSArray *tempArray  = JSON[@"data"];
        NSDictionary * dict = [tempArray firstObject];
        self.homeModel = [[HomeModel alloc] initWitDictionary:dict];
        [self setupSubView];

        NSLog(@"%@",self.homeModel);
        if ([_homeModel.ksmail isEqualToString:@"鹿城区农林水利局"]||[_homeModel.ksmail isEqualToString:@"平阳县水利局"]) {
                           self.title =[NSString stringWithFormat:@"%@OA系统",_homeModel.ksmail];

}else{
//                   self.title =[NSString stringWithFormat:@"%@OA系统(试用版2个月)",_homeModel.ksmail];
self.title =[NSString stringWithFormat:@"%@OA系统",_homeModel.ksmail];

}

    } failure:^(NSError *error) {
        
    }];
  
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSString * filePath =  [[NSBundle mainBundle] pathForResource:@"mainList" ofType:@"plist"];
    self.originalData = [NSMutableArray arrayWithContentsOfFile:filePath];
    [self.contentArray addObjectsFromArray:self.originalData];
    
    self.followLayout.sectionInset = UIEdgeInsetsMake(15, 8, 8, 8);
    self.followLayout.itemSize = CGSizeMake(([UIScreen mainScreen].bounds.size.width - 50 )/ 4 , ([UIScreen mainScreen].bounds.size.width - 50 )/ 4);
    self.followLayout.minimumLineSpacing = 20;

//    self.title = @"温州市水利局全市水利机关OA办公系统";
    [self updateApp];
    
}

//app更新提示
- (void)updateApp{
    
    //获取app版本号
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *appVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    
    
    NSArray *array = @[@{@"veseion":appVersion}];
    
    [HttpTools requestWithURL:KExchmain arrays:array method:KUpdateDownMethod success:^(id JSON) {
        
        NSArray *array = JSON[@"data"];
        
        NSDictionary *dict = [array firstObject];
        
        NSString *url = dict[@"downlink"];
        NSString *index = dict[@"result"];
        
        if ([index isEqualToString:@"1"]) {
            
// 提示更新
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"更新" message:@"程序已经更新，再重新下载" preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                if (url.length != 0) {
                    
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];

                }
                
            }];
            
            [alert addAction:cancelAction];
            [alert addAction:action];
            
            [self presentViewController:alert animated:YES completion:nil];
            
            
            
            
        }
        
    
    } failure:^(NSError *error) {
  
    
    
    }];
    
    
}

- (void)dealloc{

    [self dismissViewControllerAnimated:YES completion:nil];

}

-(void)setupSubView{
    if ([self.homeModel.whetherExchange integerValue] == 0) {
        for (NSDictionary * dict in self.contentArray) {
            if ([dict[@"title"] isEqualToString:@"待收文件"] || [dict[@"title"] isEqualToString:@"已收文件"] || [dict[@"title"] isEqualToString:@"已发文件"]) {
                [self.originalData removeObject:dict];
            }
            
        }
    }
    
    if([self.homeModel.whetherSms integerValue] == 0) {
        for (NSDictionary * dict in self.contentArray) {
            if ([dict[@"title"] isEqualToString:@"短信平台"]) {
                [self.originalData removeObject:dict];
            }
        }
    }
    
    self.contentArray = [self.originalData mutableCopy];
    [self.collectionView reloadData];
}


#pragma mark <UICollectionViewDataSource>

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.contentArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    MainViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    //cell.backgroundColor = [UIColor redColor];
    NSDictionary * dict = self.contentArray[indexPath.item];
    cell.dict = dict;
    if ([dict[@"title"]isEqualToString:@"待收文件"]) {
        [cell.btnCount setTitle:self.homeModel.exchange forState:UIControlStateNormal];
        if ([self.homeModel.exchange integerValue] !=0) {
            cell.btnCount.hidden = NO;
        }else{
            cell.btnCount.hidden = YES;
        }
    }
    else if ([dict[@"title"] isEqualToString:@"待办文件"]) {
        [cell.btnCount setTitle:self.homeModel.offiece forState:UIControlStateNormal];
        if ([self.homeModel.offiece integerValue] !=0) {
            cell.btnCount.hidden = NO;
        }else{
            cell.btnCount.hidden = YES;
        }
        
    }
    
    else if ([dict[@"title"] isEqualToString:@"待阅文件"]) {
        [cell.btnCount setTitle:self.homeModel.read forState:UIControlStateNormal];
        if ([self.homeModel.read integerValue] !=0) {
            cell.btnCount.hidden = NO;
        }else{
            cell.btnCount.hidden = YES;
        }
    }else{
        cell.btnCount.hidden = YES;
    }
    [cell layoutIfNeeded];
    return cell;
}


#pragma mark <UICollectionViewDelegate>

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
   
    [self setupWithIndexPath:indexPath];
    
}

-(void)setupWithIndexPath:(NSIndexPath*)indexPath{
    NSDictionary * dict =  self.contentArray[indexPath.item];
     OADueInViewController * dueInVC = (OADueInViewController*)[self.storyboard instantiateViewControllerWithIdentifier:@"DueInVC"];
      UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    if ([dict[@"title"] isEqualToString:@"待收文件"]) {
        dueInVC.vcType = WaitForSignType;
        [self.navigationController pushViewController:dueInVC animated:YES];
    }else if ([dict[@"title"] isEqualToString:@"已收文件"]){
        dueInVC.vcType = AlreadySignType;
        [self.navigationController pushViewController:dueInVC animated:YES];
    }else if ([dict[@"title"] isEqualToString:@"已发文件"]){
        dueInVC.vcType = SenderSinType;
        [self.navigationController pushViewController:dueInVC animated:YES];
    }else if ([dict[@"title"] isEqualToString:@"待办文件"]){
        OAUpComingWorkController * upcomingWorkVC  = (OAUpComingWorkController*)[storyBoard instantiateViewControllerWithIdentifier:@"UpComingWorkVCID"];
        [self.navigationController pushViewController:upcomingWorkVC animated:YES];
    }else if ([dict[@"title"] isEqualToString:@"已办文件"]){
        OAToDoWorkViewController * todoWorkVC  = (OAToDoWorkViewController*)[storyBoard instantiateViewControllerWithIdentifier:@"TodoWorkVCID"];
        [self.navigationController pushViewController:todoWorkVC animated:YES];
    }else if ([dict[@"title"] isEqualToString:@"待阅文件"]){
        dueInVC.vcType = WaitForReadType;
        [self.navigationController pushViewController:dueInVC animated:YES];
    }else if ([dict[@"title"] isEqualToString:@"电子公告"]){
        OANoteViewController * noteVC  = (OANoteViewController*)[storyBoard instantiateViewControllerWithIdentifier:@"noteVCID"];
        [self.navigationController pushViewController:noteVC animated:YES];
    }else if ([dict[@"title"] isEqualToString:@"最新收文"]){
        OANewInViewController * newInVC  = (OANewInViewController*)[storyBoard instantiateViewControllerWithIdentifier:@"newInVCID"];
        [self.navigationController pushViewController:newInVC animated:YES];
    }else if ([dict[@"title"] isEqualToString:@"最新发文"]){
        OANewSendViewController * sendVC  = (OANewSendViewController*)[storyBoard instantiateViewControllerWithIdentifier:@"sendVCID"];
        [self.navigationController pushViewController:sendVC animated:YES];
    }else if ([dict[@"title"] isEqualToString:@"短信平台"]){
        OASMSViewController * smsVC = (OASMSViewController*)[self.storyboard instantiateViewControllerWithIdentifier:@"SMSVCID"];
        smsVC.vcType = SMSViewControllerType;
        [self.navigationController pushViewController:smsVC animated:YES];
    }else if ([dict[@"title"] isEqualToString:@"通讯录"]){
        OAAddressViewController * addressVC = (OAAddressViewController*)[self.storyboard instantiateViewControllerWithIdentifier:@"AddressVCID"];
        [self.navigationController pushViewController:addressVC animated:YES];
    }else if ([dict[@"title"] isEqualToString:@"邮件"]){
        OAHomeEmailViewController * homeEmailVC = (OAHomeEmailViewController*)[self.storyboard instantiateViewControllerWithIdentifier:@"HomeEmailID"];
        [self.navigationController pushViewController:homeEmailVC animated:YES];
    }
}

- (IBAction)logout:(id)sender {
    
    OALoginViewController * loginVC =  [self.storyboard instantiateViewControllerWithIdentifier:@"LoginVC"];
    
    self.view.window.rootViewController = loginVC;
    
}

@end
